package com.reus.driver;

import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description: 驱动注册中心，对数据库驱动进行注册的地方
 * copyright: Copyright (c) 2018-2021
 * company: iSysCore Tech. Co., Ltd.
 *
 * @author liuxq@isyscore.com
 * @version 1.0
 * @date 2021-10-18 16:48:06
 */
public class DriverRegister {

    /**
     * description: mysql的driver类
     *
     * @modified liuxq@isyscore.com
     * @date 2021-10-18
     */
    private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";

    /**
     * description: 构建driver缓存，存储已经注册了的driver的类型
     *
     * @modified liuxq@isyscore.com
     * @date 2021-10-18
     */
    private static final Map<String, Driver> REGISTER_DRIVERS = new ConcurrentHashMap<>();

    /**
     * description: 初始化，此处是将DriverManager中已经注册了驱动放入自己缓存中。当然，你也可以在这个方法内注册,
     * 常见的数据库驱动，这样后续就可以直接使用，不用自己手动注册了。
     * @modified liuxq@isyscore.com
     * @date 2021-10-18
     */
    static {
        Enumeration<Driver> driverEnumeration = DriverManager.getDrivers();
        while (driverEnumeration.hasMoreElements()) {
            Driver driver = driverEnumeration.nextElement();
            REGISTER_DRIVERS.put(driver.getClass().getName(), driver);
        }
    }

    /**
     * description: 加载mysql驱动，此个方法可以写在静态代码块内，代表项目启动时即注册mysql驱动
     *
     * @modified liuxq@isyscore.com
     * @date 2021-10-18
     * @return: void
     */
    public void loadMySql() {
        if (!REGISTER_DRIVERS.containsKey(MYSQL_DRIVER)) {
            loadDriver(MYSQL_DRIVER);
        }
    }

    /*
     *
     * */

    /**
     * description: 加载数据库驱动通用方法，并注册到registerDrivers缓存中，此处是注册数据库驱动的方法
     *
     * @param driverName: 驱动名称
     * @modified liuxq@isyscore.com
     * @date 2021-10-18
     * @return: void
     */
    public void loadDriver(String driverName) {

        Class<?> driverType;
        try {
            // 注册驱动，返回驱动类
            driverType = Class.forName(driverName);
            // 将驱动实例放入驱动缓存中
            REGISTER_DRIVERS.put(driverType.getName(), (Driver) driverType.newInstance());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
